package com.xuecheng.auth.controller;

import com.xuecheng.api.auth.AuthControllerApi;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.framework.domain.ucenter.ext.AuthToken;
import com.xuecheng.framework.domain.ucenter.request.LoginRequest;
import com.xuecheng.framework.domain.ucenter.response.AuthCode;
import com.xuecheng.framework.domain.ucenter.response.LoginResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AuthController implements AuthControllerApi {
    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Resource
    private AuthService authService;

    /**
     * 用户登录接口
     *
     * @param loginRequest 用户登录需要的参数实体类
     * @return 用户登录返回的数据
     */
    @Override
    @PostMapping("/userLogin")
    public LoginResult userLogin(LoginRequest loginRequest) {
        if (loginRequest ==null || StringUtils.isEmpty(loginRequest.getUsername())){
            ExceptionCast.cast(AuthCode.AUTH_USERNAME_NONE);
        }
        if (StringUtils.isEmpty(loginRequest.getPassword())){
            ExceptionCast.cast(AuthCode.AUTH_PASSWORD_NONE);
        }
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();
        // 申请令牌
        AuthToken authToken = authService.userLogin(clientId, clientSecret, username, password);
        // 将令牌存储到cookie
        this.saveCookie(authToken);
        return new LoginResult(CommonCode.SUCCESS,authToken.getJti());
    }

    /**
     * 将AuthToken 存储到Cookie
     * @param authToken {@link AuthToken}
     */
    private void saveCookie(AuthToken authToken){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","uid",authToken.getJti(),cookieMaxAge,false);
    }
    /**
     * 用户注销接口
     *
     * @return 注销是否成功
     */
    @Override
    public ResponseResult userLogout() {
        return null;
    }
}
